package com.stars.services.impl;

import com.stars.common.enums.JobOperateEnum;
import com.stars.common.valid.MyException;
import com.stars.entity.job.MyScheduleJobEntity;
import com.stars.services.MyQuartzService;
import com.stars.services.impl.quartz.QuartzFactory;
import com.stars.services.job.MyScheduleJobAccessServices;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author :dj
 * @version : 1.0.0
 * @description
 * @Date 2019-10-12 13:09
 * @note
 */
@Service
@Transactional
public class MyQuartzServiceImpl implements MyQuartzService {
    /**
     * 调度器
     */
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private MyScheduleJobAccessServices myScheduleJobAccessServices;

    @Override
    public void timingTask() {
        //查询数据库是否存在需要定时的任务
        List<MyScheduleJobEntity> scheduleJobs = myScheduleJobAccessServices.selectListAll();
        if (scheduleJobs != null) {
            scheduleJobs.forEach(this::addJob);
        }
    }

    @Override
    public void addJob(MyScheduleJobEntity job) {
        try {
            //创建触发器
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getName())
                    .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                    .startNow()
                    .build();
            //创建任务
            JobDetail jobDetail = JobBuilder.newJob(QuartzFactory.class)
                    .withIdentity(job.getName())
                    .build();
            //传入调度的数据，在QuartzFactory中需要使用
            jobDetail.getJobDataMap().put("scheduleJob", job);
            //调度作业
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void operateJob(JobOperateEnum jobOperateEnum, MyScheduleJobEntity job) throws SchedulerException {
        JobKey jobKey = new JobKey(job.getName());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            throw new MyException("没有找到"+job.getName()+"定时任务");
        }
        switch (jobOperateEnum) {
            case START:
                scheduler.resumeJob(jobKey);
                break;
            case PAUSE:
                scheduler.pauseJob(jobKey);
                break;
            case DELETE:
                scheduler.deleteJob(jobKey);
                break;
        }
    }

    @Override
    public void startAllJob() throws SchedulerException {
        scheduler.start();
    }

    @Override
    public void pauseAllJob() throws SchedulerException {
        scheduler.standby();
    }
}
